from flask import Flask,request,render_template
from geventwebsocket.handler import WebSocketHandler
from geventwebsocket.websocket import WebSocket
from gevent.pywsgi import WSGIServer
import json

app = Flask(__name__)

user_socket_list = []
user_socket_dict = {}

@app.route("/ws")
def ws():
    """
    获取到websocket通讯连接
    获取信息
    发送信息
    :return:
    """
    # print("request.environ: ", request.environ)
    """
    {'GATEWAY_INTERFACE': 'CGI/1.1', 
    'SERVER_SOFTWARE': 'gevent/1.4 Python/3.7', 
    'SCRIPT_NAME': '', 'wsgi.version': (1, 0), 
    'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'SERVER_NAME': 'PC-20180730NMQX', 'SERVER_PORT': '9527', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/ws', 'QUERY_STRING': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '43709', 'HTTP_HOST': '127.0.0.1:9527', 'HTTP_CONNECTION': 'Upgrade', 'HTTP_PRAGMA': 'no-cache', 'HTTP_CACHE_CONTROL': 'no-cache', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36', 'HTTP_UPGRADE': 'websocket', 'HTTP_ORIGIN': 'http://localhost:63342', 'HTTP_SEC_WEBSOCKET_VERSION': '13', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9', 'HTTP_SEC_WEBSOCKET_KEY': 'klfkkU4OcDqdw0dCX9rAYQ==', 'HTTP_SEC_WEBSOCKET_EXTENSIONS': 'permessage-deflate; client_max_window_bits', 'wsgi.input': <gevent.pywsgi.Input object at 0x0000000004074B28>, 'wsgi.input_terminated': True, 'wsgi.websocket_version': '13', 
    'wsgi.websocket': <geventwebsocket.websocket.WebSocket object at 0x00000000039F2C78>, 
    'werkzeug.request': <Request 'http://127.0.0.1:9527/ws' [GET]>}
    """
    # 获取到socket连接
    user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
    while True:
        msg = user_socket.receive()
        print(msg)
        user_socket.send("好")
    # print(request.headers)
    # return "123"

@app.route("/qun")
def qun():
    """
    实现群聊的功能
    :return:
    """
    user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
    if user_socket:
        user_socket_list.append(user_socket)
    while True:
        msg = user_socket.receive()
        for u_socket in user_socket_list:
            if u_socket == user_socket:
                continue
            try:
                u_socket.send(msg)
            except:
                continue
            # u_socket.send("你"+msg)

@app.route("/dan/<username>")
def dan(username):
    user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
    if user_socket:
        user_socket_dict[username] = user_socket
    print(user_socket_dict)
    print(user_socket_dict)
    while True:
        msg = user_socket.receive()
        msg_dict = json.loads(msg)
        msg_dict['from_user'] = username
        to_user = msg_dict.get("to_user")
        u_socket = user_socket_dict.get(to_user)
        u_socket.send(json.dumps(msg_dict))


if __name__ == '__main__':
    http_server = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler)
    http_server.serve_forever()